package com.itheima.stock.service.impl;

import com.itheima.stock.cache.Cache;
import com.itheima.stock.constant.Constants;
import com.itheima.stock.service.UserService;
import com.itheima.stock.util.IdWorkers;
import com.itheima.stock.util.RedisKeyUtil;
import com.itheima.stock.vo.CaptchaVO;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

/**
 * ClassName: UserServiceImpl
 * Package: com.itheima.stock.service.impl
 * Description: 用户服务接口实现
 *
 * @Author Lee
 * @Create 2024/10/31
 */
@Service
public class UserServiceImpl implements UserService {

    private final IdWorkers idWorkers;
    private final Cache cache;
    /**
     * 定义随机数位数
     */

    private static final int FOUR = 4;

        this.cache = cache;
        this.idWorkers = idWorkers;
    }

    /**
     * 生成验证码
     * 1.参数校验
     * 2.核心业务处理
     * 3.数据处理返回
     *
     * @return 验证码数据
     */
    @Override
    public CaptchaVO captcha() {

        //1.生成随机4位验证码
        String captcha = RandomStringUtils.randomAlphanumeric(FOUR);
        //2.将验证码存储到Redis(key设计、架构设计)
        //2.1  生成Redis的key
        String redisKey = RedisKeyUtil.generateKey(Constants.CAPTCHA_PREFIX, idWorkers.nextStrId());
        //2.2 调用缓存接口存入验证码
        cache.set(redisKey, captcha, Constants.CAPTCHA_EXPIRE_TIME);
        // 3. 数据组装返回
        return CaptchaVO.builder()
                .rkey(redisKey)
                .code(captcha)
                .build();
    }
}
